"""启动工作环境（例如启动IDEA、Navicat、钉钉等应用）"""
# coding=utf-8
import os
import subprocess
import time

import psutil

APP_DIR_LIST = {
    "IDEA": "C:\\Program Files\\JetBrains\\IntelliJ IDEA 2021.1.3\\bin\\idea64.exe",
    "钉钉": "E:\\DingDing\\DingtalkLauncher.exe",
    "Navicat": "E:\\Navicat Premium 15\\navicat.exe",
}


def start_all_apps(app_dir_list):
    for app_name, app_dir in app_dir_list.items():
        time.sleep(0.3)
        if is_app_running(get_app_exe_name(app_dir)):
            print(app_name + "已在运行")
            continue
        print(app_name + "启动中...")
        os.startfile(app_dir)


# 关闭应用
def kill_all_apps(app_dir_list):
    for app_dir in app_dir_list.values():
        # 使用subprocess.call()可以捕获异常，使用os.system()无法做到这一点
        sys_command = "taskkill /F /IM " + get_app_exe_name(app_dir)
        try:
            subprocess.call(sys_command)
        except OSError as e:
            print(e)
            print("出错了，可能文件已经关闭")


def auto_close_cmd_window(seconds):
    for i in range(seconds, 0, -1):
        print(f"{i}秒后关闭窗口")
        time.sleep(1)


# 检查app是否已启动（防止重复启动app）
def is_app_running(app_name):
    # psutil.pids()：后台运行的所有进程的pid
    for pid in psutil.pids():
        if psutil.Process(pid).name() == app_name:
            return True
    return False


def get_app_exe_name(app_dir):
    if app_dir.split("\\")[-1] == "DingtalkLauncher.exe":
        return "DingTalk.exe"
    return app_dir.split("\\")[-1]


if __name__ == '__main__':
    start_all_apps(APP_DIR_LIST)
    auto_close_cmd_window(3)
    # kill_all_apps(APP_DIR_LIST)
